<?php 
class usersClassAction extends ActionManage
{
	public function defaultAction()
	{
		$rows = m('dept')->getall('1=1','id,name,pid','sort asc');
		$data = $this->showdept($rows,'0');
		$this->assign('deptdata', $data);
		$this->assign('maxwidth','99%');
	}
	
	private function showdept($rows,$pid)
	{
		$arr = array();
		foreach($rows as $k=>$rs){
			if($rs['pid']==$pid){
				$ren = $this->showdept($rows,$rs['id']);
				if($ren){
					$rs['children'] = $ren;
				}
				if($rs['id']=='1')$rs['open'] = true;
				$arr[] = $rs;
			}
		}
		return $arr;
	}
	
	public function dataAction()
	{
		$limit= (int)$this->get('limit','1');
		$deptid= (int)$this->get('deptid','1');
		$sort = $this->get('sort');
		$dir  = $this->get('dir');
		$order= '`sort` asc';
		if($sort && $dir)$order= '`'.$sort.'` '.$dir.'';
		$where = '1=1';
		if($deptid>1)$where='`deptid`='.$deptid.'';
		$barr = m('users')->getlimit($where, (int)$this->get('page','1'),'*',$order, $limit);
		$rows  = $barr['rows'];
		$total = count($rows);
		$barr = array(
			'rows' => $rows,
			'totalCount'=> $barr['count'],
			'success' => true,
		);
		return $barr;
	}
	
	public function formAction()
	{
		$id = (int)$this->get('id','0');
		$this->smartydata['id'] = $id;
		$rs['name'] = '';
		$rs['user'] = '';
		$rs['mobile'] = '';
		$rs['email'] = '';
		$rs['deptname'] = '';
		$rs['ranking'] = '';
		$rs['deptid'] = '0';
		$rs['face']  = '';
		$rs['type'] = '0';
		$rs['faceimg'] = 'images/noface.png';
		if($id>0){
			$rs = m('users')->getone('`id`='.$id.'');
			$rs['faceimg'] = 'images/noface.png';
			if($rs['face'])$rs['faceimg'] = $rs['face'];
		}
		$this->smartydata['rs'] = $rs;
	}
	
	public function savecheckAction()
	{
		$name = $this->post('name');
		$user = $this->post('user');
		$pass = $this->post('pass');
		$mobile = $this->post('mobile');
		$id = (int)$this->post('id','0');
		
		if(m('users')->rows("`user`='$user' and `id`<>'$id'")>0)return '用户名已经存在了';
		if($mobile && m('users')->rows("`mobile`='$mobile' and `id`<>'$id'")>0)return '手机号已经存在了';
		
		$uarr= array(
			'name' 	=> $name,
			'user' 	=> $user,
			'mobile' 	=> $this->post('mobile'),
			'email' 	=> $this->post('email'),
			'deptname' 	=> $this->post('deptname'),
			'ranking' 	=> $this->post('ranking'),
			'face' 	=> $this->post('face'),
			'type' 	=> (int)$this->post('type'),
			'deptid' 	=> (int)$this->post('deptid'),
		);
		$where = '`id`='.$id.'';
		if($id==0){
			if(isempt($pass))$pass = '123456';
			$where = '';
			$uarr['status']=1;
			$uarr['regdt'] = $this->rock->now;
		}
		if(!isempt($pass)){
			$rand = rand(100000,999999);
			$uarr['pass'] = md5($pass.$rand);
			$uarr['rand'] = $rand;
		}
		
		$bo 	= m('users')->record($uarr, $where);
		if(!$bo)return $this->db->error();
		
		return 'ok';
	}
	
}